package pl.wroc.pwr.docs.repos.webapp.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import pl.wroc.pwr.docs.repos.webapp.repo.DocumentDao;
import pl.wroc.pwr.docs.repos.webapp.web.Message.STATUS;

@WebServlet(urlPatterns="/add-document")
public class DocumentAddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String filepath = req.getParameter("filepath");
		ServletContext context = getServletContext();
		MessageQueue messages = ((MessageQueue) req.getSession().getAttribute("messages"));
		DataSource ds = (DataSource) context.getAttribute("connectionPool");
		Connection con = null;
		
		try {
			con = ds.getConnection();
			DocumentDao dao = new DocumentDao(con);
			File file = new File(filepath);
			FileInputStream in = new FileInputStream(file);
			int id = dao.addDocument(file.getName(), in, file.getAbsolutePath());
			System.out.println(id);
			dao.addIndexedContent(id, dao.getContent(id,1000));
			messages.push( new Message(STATUS.SUCCESS, "Dokument został dodany pomyślnie.") );
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			messages.push(new Message(STATUS.ERROR, "Nie ma takiego pliku."));
		} catch (Exception e) {
			e.printStackTrace();
			messages.push(new Message(STATUS.ERROR, "Operacja się nie udała."));
			
		} finally {
			if (con != null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		resp.sendRedirect("/index.jsp#add");
	}
}